//
//  ICChatViewController+sendMessage.m
//  ICome
//
//  Created by zhangrongwu on 2017/1/5.
//  Copyright © 2017年 iCom. All rights reserved.
//

#import "ICChatViewController+sendMessage.h"
#import "NSData+Image.h"
//重构修改
#import "ICReceiveShareObject.h"
#import "ICMediaManager.h"
#import "ICRecordManager.h"
#import "ICFileTool.h"
#import "ICSendMessageHelper.h"

@implementation ICChatViewController (sendMessage)
#pragma mark - Send Message
/**
 消息发送出口
 */
- (void)sendMessage:(ICMessage *)message
           messageF:(ICMessageFrame *)messageF
{
    NSString *identifier = message.messageId;
    NSLog(@"消息唯一id: %@", identifier);
    
    [self saveUnSendMessageF:messageF Message:message];
    
    WEAKSELF
    [ICSendMessageHelper sendMessageWithObject:[ICMessageHelper createSendParamWithMessage:message]
                                    identifier:identifier
                                       Success:^(id object, id other) {
                                           [weakSelf setMessageStatus:YES object:object other:other];
                                       } Failure:^(NSError *error, id other) {
                                           [weakSelf setMessageStatus:NO object:error other:other];
                                           NSLog(@"消息发送失败:%@",error);
                                       }];
}

- (void)setMessageStatus:(BOOL)success object:(id)object other:(id)other {
    NSString *identify = other[@"identify"];
    for (ICMessageFrame *messageF in self.dataSource) {
        if ([identify isEqualToString:messageF.model.message.messageId]||[identify isEqualToString:messageF.model.message.localMsgId]) { // 同一条消息
            if (success) {
                [self messageSendSucceedWithDic:object messageF:messageF identifier:identify];
            } else {
                [self messageSendFailued:messageF];
            }
            return;
        }
    }
}

/**
 所有的消息都先保存后发送
 */
- (void)saveUnSendMessageF:(ICMessageFrame *)messageF Message:(ICMessage *)message {
    messageF.model.message.deliveryState = ICMessageDeliveryState_Delivering;
    messageF.model.message.messageId = message.messageId;
    // 未发送时先给本地时间
    [ICMessageDatabase saveMessage:messageF.model];
}


/**
 发送正常文本消息
 */
- (void)sendTextMessageWithContent:(NSString *)messageStr
{
    ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypeText
                                                           content:messageStr
                                                              path:nil
                                                              from:[ICUser currentUser].eId
                                                                to:self.group.gId
                                                               lnk:nil
                                                           fileKey:nil
                                                          isSender:YES
                                          receivedSenderByYourself:NO];
    [self sendTextMessage:messageStr messageF:messageF];
    [self addObject:messageF isSender:YES];
}



- (void)sendTextMessage:(NSString *)content
               messageF:(ICMessageFrame *)messageF
{
    ICMessage *message = [ICMessageHelper createSendMessageF:messageF
                                                     Message:TypeText
                                                     content:content
                                                     fileKey:nil
                                                        from:[ICUser currentUser].eId
                                                          to:self.group.gId
                                                         lnk:nil
                                                      status:nil];
    [self sendMessage:message messageF:messageF];
}


/**
 发送 @ 消息
 */
- (void)sendATTextMessageWithContent:(NSString *)messageStr
{
    ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypeAtText
                                                           content:messageStr
                                                              path:nil
                                                              from:[ICUser currentUser].eId
                                                                to:self.group.gId
                                                               lnk:nil
                                                           fileKey:[self.Mutabledict jsonString]
                                                          isSender:YES
                                          receivedSenderByYourself:NO];
    [self sendATTextMessage:messageStr messageF:messageF];
    // 菊花转起来
    [self addObject:messageF isSender:YES];
}

- (void)sendATTextMessage:(NSString *)content
                 messageF:(ICMessageFrame *)messageF
{
    ICMessage *message = [ICMessageHelper createSendMessageF:messageF
                                                     Message:TypeAtText
                                                     content:content
                                                     fileKey:messageF.model.message.fileKey
                                                        from:[ICUser currentUser].eId
                                                          to:self.group.gId
                                                         lnk:nil
                                                      status:nil];
    
    [self sendMessage:message messageF:messageF];
}


/**
 发送图文链接消息
 */
- (void)sendPicTextMessageWithContent:(ICReceiveShareObject *)shareObject
{
    ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypePicText
                                                           content:shareObject.message.title
                                                              path:nil
                                                              from:[ICUser currentUser].eId
                                                                to:self.group.gId
                                                               lnk:shareObject.webPageObject.webpageUrl
                                                           fileKey:nil
                                                          isSender:YES
                                          receivedSenderByYourself:NO];
    messageF.model.message.lnk = shareObject.webPageObject.webpageUrl;
    NSDictionary *key = @{
                          @"filekey":@"", // 目前还没
                          @"summary":shareObject.message.desc,
                          @"source" :shareObject.message.displayName
                          };
    messageF.model.message.fileKey = [key jsonString];
    
    messageF.model.message.messageId = [ICMessageHelper localMessageId:@"[链接]"];
    messageF.model.message.localMsgId = messageF.model.message.messageId;
    messageF.model.message.date = [ICMessageHelper currentMessageTime];
    messageF.model.message.reSend = 1; // 直接写成重发
    messageF.model.message.isAnimation = NO; // 关闭刷新
    
    NSString *imgPath = [[ICMediaManager sharedManager] saveImage:[UIImage imageWithData:shareObject.message.thumbData]];
    messageF.model.mediaPath = imgPath;
    [self sendPicTextMessage:shareObject messageF:messageF imgPath:imgPath];
    [self addObject:messageF isSender:YES];
}

// 发送图文链接
- (void)sendPicTextMessage:(ICReceiveShareObject *)shareObject
                  messageF:(ICMessageFrame *)messageF
                   imgPath:(NSString *)imgPath
{
    ICMessage *message = [ICMessageHelper createSendMessageF:messageF
                                                     Message:TypePicText
                                                     content:messageF.model.message.content
                                                     fileKey:nil
                                                        from:[ICUser currentUser].eId
                                                          to:self.group.gId
                                                         lnk:messageF.model.message.lnk
                                                      status:nil];
    // 发送图片拿到filekey
    WEAKSELF
    [[ICNetworkManager sharedInstance] sendImage:shareObject.message.thumbData imgName:[imgPath lastPathComponent] progress:^(NSProgress *pro) {
        
    } success:^(id object) {
        NSString *fileKey = [object objectForKey:@"data"];
        NSDictionary *key = @{
                              @"filekey":fileKey,
                              @"summary":shareObject.message.desc,
                              @"source":shareObject.message.displayName
                              };
        messageF.model.message.fileKey = [key jsonString];
        message.fileKey = [key jsonString];
        [weakSelf sendMessage:message messageF:messageF];
    } failure:^(NSError *error) {
        NSLog(@"share image send failured:%@",error);
    }];
}



/**
 发送图片消息
 */
- (void)sendImageMessageWithImgPath:(NSString *)imgPath
{
    UIImage *image = [[ICMediaManager sharedManager] imageWithLocalPath:imgPath];
    NSDictionary * dic = @{@"w":[NSString stringWithFormat:@"%.0f",image.size.width],
                           @"h":[NSString stringWithFormat:@"%.0f",image.size.height]};
    NSString *lnk = [dic jsonString];
    NSString *content = @"[图片]";
    ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypePic
                                                           content:content
                                                              path:imgPath
                                                              from:[ICUser currentUser].eId
                                                                to:self.group.gId
                                                               lnk:lnk
                                                           fileKey:nil
                                                          isSender:YES
                                          receivedSenderByYourself:NO];
    // 构造重发结构（实际为第一次发送，让走重发逻辑）
    messageF.model.message.locImgPath = imgPath;
    messageF.model.message.messageId = [ICMessageHelper localMessageId:content];
    messageF.model.message.localMsgId = messageF.model.message.messageId;
    messageF.model.message.date = [ICMessageHelper currentMessageTime];
    messageF.model.message.reSend = 1; // 直接写成重发
    messageF.model.message.isAnimation = NO; // 关闭刷新
    [self saveUnSendMessageF:messageF Message:messageF.model.message];
    // 数据添加到原始数组中
    [self addObject:messageF isSender:YES];
    // 相当于重新发送图片文件处理逻辑
    [self sendImageMessage:imgPath messageF:messageF];
}

- (void)sendImageMessage:(NSString *)imgPath
                messageF:(ICMessageFrame *)messageF
{
    UIImage *image = [[ICMediaManager sharedManager] imageWithLocalPath:imgPath];
    NSString *imgName = [[[imgPath lastPathComponent] stringByDeletingPathExtension] stringByAppendingPathExtension:@"jpeg"];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.9); // jpeg更小
    
    WEAKSELF
    [[ICNetworkManager sharedInstance] sendImage:imageData imgName:imgName progress:^(NSProgress *pro) {
        
    } success:^(id object) {
        NSString *fileKey = [object objectForKey:@"data"];
        messageF.model.message.fileKey = fileKey;
        [weakSelf sendFileKey:fileKey messageF:messageF content:@"[图片]" messageType:TypePic];
    } failure:^(NSError *error) {
        NSLog(@"sendImageMessage-failure:%@",error);
        [weakSelf messageSendFailued:messageF];
    }];
}

/**
 发送语音消息
 */
- (void)sendVoiceMessage:(NSString *)voicePath
                messageF:(ICMessageFrame *)messageF
{
    NSData *voiceData = [NSData dataWithContentsOfFile:voicePath];
    if(voiceData == nil){
        [MBProgressHUD showError:@"语音发送错误"];
        return;
    }
    
    NSString *voiceName = [voicePath lastPathComponent];
    WEAKSELF
    [[ICNetworkManager sharedInstance] sendMedia:voiceData mediaName:voiceName success:^(id object) {
        // 应该把wav文件删除
        NSString *fileKey = [object objectForKey:@"data"];
        messageF.model.message.fileKey = fileKey;
        [weakSelf sendFileKey:fileKey messageF:messageF content:@"[语音]" messageType:TypeVoice];
        
    } failure:^(NSError *error) {
        [weakSelf messageSendFailued:messageF];
    }];
}

// 语音发送
- (void)sendVoiceMessage:(NSString *)duration
               voicePath:(NSString *)voicePath {
    NSString *content = @"[语音]";
    ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypeVoice
                                                           content:content
                                                              path:voicePath
                                                              from:[ICUser currentUser].eId
                                                                to:self.group.gId
                                                               lnk:duration
                                                           fileKey:nil
                                                          isSender:YES
                                          receivedSenderByYourself:NO];
    // 构造重发结构
    messageF.model.message.messageId = [ICMessageHelper localMessageId:content];
    messageF.model.message.localMsgId = messageF.model.message.messageId;
    messageF.model.message.date = [ICMessageHelper currentMessageTime];
    messageF.model.message.reSend = 1; // 直接写成重发
    messageF.model.message.isAnimation = NO; // 关闭刷新
    
    [self saveUnSendMessageF:messageF Message:messageF.model.message];
    
    // 添加到原始数据中
    [self addObject:messageF isSender:YES];
    
    //走重发逻辑 保证正常显示
    [self sendVoiceMessage:voicePath messageF:messageF];
}

/**
 发送视频消息
 */
- (void)sendVideoMessage:(NSString *)videoPath
                messageF:(ICMessageFrame *)messageF
{
    NSData *videoData   = [NSData dataWithContentsOfFile:videoPath];
    NSString *videoName = [videoPath lastPathComponent];
    WEAKSELF
    [[ICNetworkManager sharedInstance] sendMedia:videoData mediaName:videoName success:^(id object) {
        
        NSString *fileKey = [object objectForKey:@"data"];
        messageF.model.message.fileKey = fileKey;
        [weakSelf sendFileKey:fileKey messageF:messageF content:@"[视频]" messageType:TypeVideo];
        
    } failure:^(NSError *error) {
        NSLog(@"sendVideoMessage-failure:%@",error);
        [weakSelf messageSendFailued:messageF];
    }];
}

/**
 发送Zoom视频会议
 */
-(void)sendZoomVideoMessage:(NSString *)message
{
    NSString *title = @"视频会议";
    if ([self.group.gType isEqualToString:@"1"]) {
        title = [NSString stringWithFormat:@"%@和%@的视频会议", self.title, [ICUser currentUser].eName];
    } else if ([self.group.gType isEqualToString:@"2"]) {
        title = [NSString stringWithFormat:@"%@的视频会议", self.title];
    }
    NSDictionary * dic = @{@"title":title,
                           @"beginDate":[NSString stringWithFormat:@"%ld",[ICMessageHelper currentMessageTime]],
                           @"host":[ICUser currentUser].eName,
                           @"vcId":message
                           };
    NSString *key = [dic jsonString];
    NSString *content = title;
    ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypeVideoConference
                                                           content:content
                                                              path:nil
                                                              from:[ICUser currentUser].eId
                                                                to:self.group.gId
                                                               lnk:nil
                                                           fileKey:key
                                                          isSender:YES
                                          receivedSenderByYourself:NO];
    [self sendZoomVideoModelFrame:messageF];
    [self addObject:messageF isSender:YES];
}

- (void)sendZoomVideoModelFrame:(ICMessageFrame *)modelFrame
{
    ICMessage *message = [ICMessageHelper createSendMessageF:modelFrame
                                                     Message:TypeVideoConference
                                                     content:modelFrame.model.message.content
                                                     fileKey:modelFrame.model.message.fileKey
                                                        from:[ICUser currentUser].eId
                                                          to:self.group.gId
                                                         lnk:nil
                                                      status:nil];
    
    [self sendMessage:message messageF:modelFrame];
}

- (void)sendVideoImage:(ICMessageFrame *)modelFrame
             videoPath:(NSString *)videoPath
{
    UIImage *thumbnailImage = [UIImage videoFramerateWithPath:modelFrame.model.mediaPath];
    NSUInteger duration = [[ICRecordManager shareManager] durationWithVideo:[NSURL fileURLWithPath:videoPath]];
    NSString *name = [NSString currentName];
    NSString *imgName = [NSString stringWithFormat:@"%@.png",name];
    NSData *imageData = UIImagePNGRepresentation(thumbnailImage);
    
    NSDictionary *dic = @{@"w":[NSString stringWithFormat:@"%.0f",thumbnailImage.size.width],
                          @"h":[NSString stringWithFormat:@"%.0f",thumbnailImage.size.height],
                          @"t":[NSString stringWithFormat:@"%ld",duration],
                          @"id":@""};
    modelFrame.model.message.lnk = [dic jsonString];
    
    // 构造重发结构（实际为第一次发送，让走重发逻辑）
    modelFrame.model.message.locImgPath = modelFrame.model.mediaPath;
    modelFrame.model.message.messageId = [ICMessageHelper localMessageId:@"[视频]"];
    modelFrame.model.message.localMsgId = modelFrame.model.message.messageId;
    modelFrame.model.message.date = [ICMessageHelper currentMessageTime];
    modelFrame.model.message.reSend = 1; // 直接写成重发
    modelFrame.model.message.isAnimation = NO; // 关闭刷新
    
    [self saveUnSendMessageF:modelFrame Message:modelFrame.model.message];
    
    [self addObject:modelFrame isSender:YES];
    
    
    WEAKSELF
    [[ICNetworkManager sharedInstance] sendImage:imageData imgName:imgName progress:nil success:^(id object) {
        NSString *imgKey = [object objectForKey:@"data"];
        NSDictionary *dic = @{
                              @"w":[NSString stringWithFormat:@"%.0f",thumbnailImage.size.width],
                              @"h":[NSString stringWithFormat:@"%.0f",thumbnailImage.size.height],
                              @"t":[NSString stringWithFormat:@"%ld",duration],
                              @"id":imgKey
                              };
        modelFrame.model.message.lnk = [dic jsonString];
        [weakSelf sendVideoMessage:videoPath messageF:modelFrame];
    } failure:^(NSError *error) {
        NSLog(@"sendVideoImage-failure:%@",error);
    }];
}

- (void)sendFileMessageWithFileName:(NSString *)fileName {
    NSString *lastName = [fileName originName];
    NSString*fileKey   = [fileName firstStringSeparatedByString:@"_"];
    NSString *content = [NSString stringWithFormat:@"[文件]%@",lastName];
    ICMessageFrame *messageFrame = [ICMessageHelper createMessageFrame:TypeFile
                                                               content:content
                                                                  path:fileName
                                                                  from:[ICUser currentUser].eId
                                                                    to:self.group.gId
                                                                   lnk:nil
                                                               fileKey:nil
                                                              isSender:YES
                                              receivedSenderByYourself:NO];
    NSString *path = [[ICFileTool fileMainPath] stringByAppendingPathComponent:fileName];
    double s = [ICFileTool fileSizeWithPath:path];
    NSNumber *x = [ICMessageHelper fileType:[fileName pathExtension]];
    if (!x) {
        x = @0;
    }
    NSDictionary *lnk = @{@"s":@((long)s),@"x":x,@"n":lastName};
    messageFrame.model.message.lnk = [lnk jsonString];
    messageFrame.model.message.fileKey = fileKey;
    //    [self sendFileMessage:messageFrame filePath:path resend:NO];
    [self sendFile:messageFrame path:path];
    [self addObject:messageFrame isSender:YES];
}
/**
 发送文件消息
 */
- (void)sendFileMessage:(ICMessageFrame *)messageF
               filePath:(NSString *)filePath
{
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    NSString *fileName = [filePath lastPathComponent];
    NSString *trueName = [fileName originName];
    WEAKSELF
    [[ICNetworkManager sharedInstance] sendFile:fileData fileName:trueName progress:^(NSProgress * po) {
        
    } success:^(id object) {
        
        NSDictionary * data = [object objectForKey:@"data"];
        NSString *fileKey   = [data objectForKey:@"fileKey"];
        NSInteger size      = [[data objectForKey:@"size"] integerValue];
        int type            = [[data objectForKey:@"type"] intValue];
        NSDictionary *lnk = @{@"s":@(size),@"x":@(type),@"n":trueName};
        messageF.model.message.lnk = [lnk jsonString];
        messageF.model.message.fileKey = fileKey;
        
        [weakSelf sendFileKey:fileKey messageF:messageF content:messageF.model.message.content messageType:TypeFile];
        // 一般情况下是不需要重新上传文件的，但这里上传文件了，那么copy一份并重命名
        NSString *copyPath =  [ICFileTool filePathWithName:fileKey orgName:[trueName stringByDeletingPathExtension] type:[filePath pathExtension]];
        [ICFileTool copyFileAtPath:filePath toPath:copyPath];
    } failure:^(NSError *error) {
        NSLog(@"sendFileMessage-failure:%@",error);
        [weakSelf messageSendFailued:messageF];
    }];
}

// 发文件消息
- (void)sendFile:(ICMessageFrame *)messageF
            path:(NSString *)path
{
    // 命名格式是否正确
    NSString *fileLocalName =  messageF.model.mediaPath; //这里传递的fileName
    NSArray *arr = [fileLocalName componentsSeparatedByString:@"_"];
    if (arr.count > 1) { // 校验文件格式
        [self checkFilekey:messageF.model.message.fileKey path:path messageF:messageF];
    } else {  // 发送
        [self sendFileMessage:messageF filePath:path];
    }
}

// 校验文件
- (void)checkFilekey:(NSString *)fileKey
                path:(NSString *)path
            messageF:(ICMessageFrame *)messageF
{
    __weak typeof(self) weakSelf = self;
    [[ICNetworkManager sharedInstance] checkFileKey:fileKey success:^(NSDictionary *object) {
        NSDictionary *data = [object objectForKey:@"data"];
        NSString *md5      = [data objectForKey:@"md5"];
        NSInteger size     = [[data objectForKey:@"size"] integerValue];
        int      type      = [[data objectForKey:@"type"] intValue];
        NSString *localMd5 = [ICMD5 fileMD5WithPath:path];
        NSString *currentName = [[path lastPathComponent] originName];
        if ([md5 isEqualToString:localMd5]) {
            NSDictionary *lnk = @{@"s":@(size),@"x":@(type),@"n":currentName};
            messageF.model.message.lnk = [lnk jsonString];
            messageF.model.message.content = [NSString stringWithFormat:@"[文件]%@",currentName];
            [weakSelf sendFileKey:fileKey messageF:messageF content:messageF.model.message.content messageType:TypeFile];
        } else { // 服务器上没有一模一样内容的文件了
            [weakSelf sendFileMessage:messageF filePath:path];
        }
        
    } failure:^(NSError *error) {
        [weakSelf messageSendFailued:messageF];
        NSLog(@"checkFilekey error :%@",error);
    }];
}


/**
 发送文件的fileKey给长连接服务器
 */
- (void)sendFileKey:(NSString *)fileKey
           messageF:(ICMessageFrame *)messageF
            content:(NSString *)content
        messageType:(NSString *)messageType
{
    ICMessage *message = [ICMessageHelper createSendMessageF:messageF
                                                     Message:messageType
                                                     content:content
                                                     fileKey:fileKey
                                                        from:[ICUser currentUser].eId
                                                          to:self.group.gId
                                                         lnk:messageF.model.message.lnk
                                                      status:nil];
    [self sendMessage:message
             messageF:messageF];
}

/**
 消息发送失败样式
 */
- (void)messageFailuedStatusWithMessageF:(ICMessageFrame *)messageF
{
    messageF.model.message.deliveryState = ICMessageDeliveryState_Failure;
    [self reloadTableView];
}

/**
 消息发送成功样式
 */
- (void)messageSendSucceedWithDic:(NSDictionary *)data
                         messageF:(ICMessageFrame *)messageF
                       identifier:(NSString *)identifier
{
    BOOL isReSend = messageF.model.message.reSend > 0 ? YES : NO;
    BOOL Animation = messageF.model.message.isAnimation;
    if (isReSend && Animation) {  // 重发的操作
        NSInteger inde = [self.dataSource indexOfObject:messageF];
        [self.dataSource removeObject:messageF];
        [self.tableView beginUpdates];
        [self.tableView deleteRowAtIndexPath:[NSIndexPath indexPathForRow:inde inSection:0] withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView endUpdates];
    }
    
    messageF.model.message.deliveryState = ICMessageDeliveryState_Delivered;
    messageF.model.message.messageId = [data objectForKey:@"id"];
    messageF.model.message.to = [data objectForKey:@"gId"];
    messageF.model.message.date = [[data objectForKey:@"st"] integerValue];// 服务器时间
    
    if (isReSend && Animation) {
        [self.dataSource addObject:messageF];
        [self.tableView beginUpdates];
        [self.tableView insertRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataSource.count-1 inSection:0] withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView endUpdates];
    } else {
        // 成功样式
        messageF.model.message.deliveryState = ICMessageDeliveryState_Delivered;
        [self reloadTableView];
    }
    [self scrollToBottomAnimated:YES];
}

/**
 消息发送失败样式
 */
- (void)messageSendFailued:(ICMessageFrame *)messageF
{
    messageF.model.message.deliveryState = ICMessageDeliveryState_Failure;
    [self messageFailuedStatusWithMessageF:messageF];
}

/**
 单独保存红包消息
 */
- (void)saveRedPacket:(ICMessageFrame *)messageF Message:(ICMessage *)message {
    messageF.model.message.deliveryState = ICMessageDeliveryState_Delivered;
    messageF.model.message.messageId = message.messageId;
    // 未发送时先给本地时间
    [ICMessageDatabase saveMessage:messageF.model];
}

@end
